"""
RagFlow 客户端 PySide6 GUI 应用
提供现代化的图形界面操作 RagFlow 客户端
"""

import os
import sys
from typing import Dict, List, Optional, Tuple

from PySide6.QtCore import Qt, Signal, Slot
from PySide6.QtGui import QFont
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QCheckBox, QPushButton, QMessageBox, QFrame
)

from ragflow_client.config import RagFlowConfig
from ragflow_client.utils.logger import get_logger
from ragflow_client.gui.components.home_grid import HomeGridWidget
# 移除不再使用的导入

from ragflow_client.gui.features import (
    ConfigFeature, UploadFeature, BatchUploadFeature, LogFeature,
    DatasetsFeature, DocumentsFeature, SearchFeature, ChatFeature, HomeFeature
)

logger = get_logger(__name__)


class RagFlowClientApp(QMainWindow):
    """RagFlow 客户端 PySide6 GUI 应用类"""
    
    def __init__(self):
        """初始化 GUI 应用"""
        super().__init__()
        
        # 设置窗口属性
        self.setWindowTitle("RagFlow 客户端")
        self.setMinimumSize(800, 600)
        
        # 加载配置
        self.load_config()
        
        # 应用主题
        self.apply_theme()
        
        # 创建界面
        self.setup_ui()
        
        # 当前工作线程
        self.current_thread = None
    
    def apply_theme(self):
        """应用主题样式"""
        logger.debug(f"应用主题: {self.config.theme}")
        
        # 确保中央部件存在
        if not hasattr(self, 'centralWidget') or not self.centralWidget():
            logger.warning("中央部件不存在，无法应用主题")
            return
            
        # 移除所有可能的边框
        self.setStyleSheet("QMainWindow { border: none; }")
            
        if self.config.theme == "dark":
            # 暗黑模式样式
            style = """
                QMainWindow, QWidget {
                    background-color: #2d2d2d;
                    color: #f0f0f0;
                    border: none;
                }
                #versionLabel {
                    background-color: transparent;
                    color: #f0f0f0;
                    font-weight: bold;
                    font-size: 12pt;
                    border: none;
                    padding: 5px;
                }
                #homeWidget {
                    background-color: transparent;
                    border: none;
                }
                QGridLayout, QVBoxLayout, QHBoxLayout {
                    spacing: 3px;
                }
                QLabel {
                    color: #f0f0f0;
                    background-color: transparent;
                }
                QLineEdit, QTextEdit {
                    background-color: #3d3d3d;
                    color: #f0f0f0;
                    border: 1px solid #555555;
                    border-radius: 3px;
                    padding: 2px;
                }
                QPushButton {
                    background-color: #444444;
                    color: #f0f0f0;
                    border: 1px solid #555555;
                    border-radius: 3px;
                    padding: 5px;
                }
                QPushButton:hover {
                    background-color: #555555;
                }
                QPushButton:pressed {
                    background-color: #666666;
                }
                QCheckBox {
                    color: #f0f0f0;
                }
                QCheckBox::indicator {
                    width: 13px;
                    height: 13px;
                    border: 1px solid #555555;
                    background-color: #3d3d3d;
                }
                QCheckBox::indicator:checked {
                    background-color: #007bff;
                }
                /* 下拉框样式 */
                QComboBox {
                    background-color: #3d3d3d;
                    color: #f0f0f0;
                    border: 1px solid #555555;
                    border-radius: 3px;
                    padding: 2px 5px;
                    min-width: 150px;
                }
                QComboBox::drop-down {
                    subcontrol-origin: padding;
                    subcontrol-position: top right;
                    width: 20px;
                    border-left: 1px solid #555555;
                }
                QComboBox QAbstractItemView {
                    background-color: #3d3d3d;
                    color: #f0f0f0;
                    selection-background-color: #555555;
                }
                /* 九宫格按钮样式 */
                HomeGridWidget QPushButton {
                    padding: 10px;
                    border: 1px solid #555555;
                    border-radius: 10px;
                    background-color: #3d3d3d;
                }
                HomeGridWidget QPushButton:hover {
                    background-color: #4d4d4d;
                    border: 1px solid #666666;
                }
                HomeGridWidget QPushButton:pressed {
                    background-color: #5d5d5d;
                }
                HomeGridWidget QLabel {
                    color: #f0f0f0;
                }
            """
        else:
            # 浅色模式样式
            style = """
                QMainWindow, QWidget {
                    background-color: white;
                    color: #333333;
                    border: none;
                }
                QGridLayout, QVBoxLayout, QHBoxLayout {
                    spacing: 3px;
                }
                QLabel {
                    color: #333333;
                    background-color: transparent;
                }
                QLineEdit, QTextEdit {
                    background-color: white;
                    color: #333333;
                    border: 1px solid #cccccc;
                    border-radius: 3px;
                    padding: 2px;
                }
                QPushButton {
                    background-color: #f0f0f0;
                    color: #333333;
                    border: 1px solid #cccccc;
                    border-radius: 3px;
                    padding: 5px;
                }
                QPushButton:hover {
                    background-color: #e0e0e0;
                }
                QPushButton:pressed {
                    background-color: #d0d0d0;
                }
                QCheckBox {
                    color: #333333;
                }
                QCheckBox::indicator {
                    width: 13px;
                    height: 13px;
                    border: 1px solid #cccccc;
                    background-color: white;
                }
                QCheckBox::indicator:checked {
                    background-color: #007bff;
                }
                /* 下拉框样式 */
                QComboBox {
                    background-color: white;
                    color: #333333;
                    border: 1px solid #cccccc;
                    border-radius: 3px;
                    padding: 2px 5px;
                    min-width: 150px;
                }
                QComboBox::drop-down {
                    subcontrol-origin: padding;
                    subcontrol-position: top right;
                    width: 20px;
                    border-left: 1px solid #cccccc;
                }
                QComboBox QAbstractItemView {
                    background-color: white;
                    color: #333333;
                    selection-background-color: #e0e0e0;
                }
                /* 九宫格按钮样式 */
                HomeGridWidget QPushButton {
                    padding: 10px;
                    border: 1px solid #ccc;
                    border-radius: 10px;
                    background-color: #f0f0f0;
                }
                HomeGridWidget QPushButton:hover {
                    background-color: #e0e0e0;
                    border: 1px solid #aaa;
                }
                HomeGridWidget QPushButton:pressed {
                    background-color: #d0d0d0;
                }
                HomeGridWidget QLabel {
                    color: #333333;
                }
            """
        
        # 应用样式
        self.setStyleSheet(style)
        
        # 强制更新所有子部件
        self.centralWidget().setStyleSheet("background-color: transparent; border: none;")
        
        # 更新所有子窗口
        for window in QApplication.topLevelWidgets():
            if window != self and isinstance(window, QWidget):
                window.setStyleSheet(style)
        
        # 强制重绘
        self.repaint()
        QApplication.processEvents()
        
        logger.debug("主题应用完成")
    
    def load_config(self) -> None:
        """加载配置"""
        try:
            self.config = RagFlowConfig.from_env()
        except Exception as e:
            # 如果加载失败，创建默认配置
            logger.warning(f"加载配置失败: {str(e)}，将使用默认配置")
            self.config = RagFlowConfig(
                api_url="",
                api_key="",
                kb_id="",
                kb_name="",
                parser_id="naive",
                doc_dir="",
                doc_suffix=["md", "txt", "pdf", "docx"],
                debug=False
            )
    
    def create_home_grid(self) -> None:
        """创建九宫格主页"""
        # 创建主页布局
        home_layout = QVBoxLayout(self.home_widget)
        
        # 创建九宫格组件
        self.home_grid = HomeGridWidget(self)
        home_layout.addWidget(self.home_grid)
        
        # 连接信号
        self.home_grid.show_tab_signal.connect(self.show_tab)
        self.home_grid.show_datasets_signal.connect(self.show_datasets)
        self.home_grid.show_documents_signal.connect(self.show_documents)
        self.home_grid.show_search_signal.connect(self.show_search)
        self.home_grid.show_chat_signal.connect(self.show_chat)
        self.home_grid.show_home_signal.connect(self.show_home)
    
    def setup_ui(self) -> None:
        """创建界面"""
        # 创建中央部件
        central_widget = QWidget()
        central_widget.setAutoFillBackground(True)  # 确保背景被填充
        central_widget.setObjectName("centralWidget")
        # 不在这里设置背景颜色，而是通过apply_theme方法统一设置
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)  # 移除主布局的边距
        main_layout.setSpacing(0)  # 移除布局元素之间的间距
        
        # 直接在主布局中添加版本号标签，不使用单独的标题栏
        version_label = QLabel("RagFlow 客户端 v0.19.0")
        version_label.setObjectName("versionLabel")
        version_label.setAlignment(Qt.AlignCenter)
        font = QFont()
        font.setBold(True)
        font.setPointSize(12)
        version_label.setFont(font)
        version_label.setContentsMargins(5, 5, 5, 5)
        version_label.setAutoFillBackground(False)  # 不填充背景
        main_layout.addWidget(version_label)
        
        # 主页部件
        self.home_widget = QWidget()
        self.home_widget.setObjectName("homeWidget")
        self.home_widget.setAutoFillBackground(False)  # 不填充背景
        main_layout.addWidget(self.home_widget)
        
        # 创建九宫格主页
        self.create_home_grid()
        
        # 创建状态栏
        self.statusBar().showMessage("就绪")
    
    def show_tab(self, index: int) -> None:
        """
        显示指定的选项卡
        
        Args:
            index: 选项卡索引
        """
        # 根据索引使用对应的功能模块
        if index == 0:
            config_feature = ConfigFeature(self)
            config_feature.execute()
        elif index == 1:
            upload_feature = UploadFeature(self)
            upload_feature.execute()
        elif index == 2:
            batch_upload_feature = BatchUploadFeature(self)
            batch_upload_feature.execute()
        elif index == 3:
            log_feature = LogFeature(self)
            log_feature.execute()
    
    def show_home(self) -> None:
        """显示主页"""
        # 使用返回主页功能模块
        home_feature = HomeFeature(self)
        home_feature.execute()
    
    def show_datasets(self) -> None:
        """显示知识库列表"""
        # 使用知识库列表功能模块
        datasets_feature = DatasetsFeature(self)
        datasets_feature.execute()
    
    # 这个方法已经被移动到 DatasetsFeature 类中
    
    def show_documents(self) -> None:
        """显示文档列表"""
        # 使用文档列表功能模块
        documents_feature = DocumentsFeature(self)
        documents_feature.execute()
    
    # 这些方法已经被移动到 DocumentsFeature 类中
    
    def show_search(self) -> None:
        """显示搜索界面"""
        # 使用搜索功能模块
        search_feature = SearchFeature(self)
        search_feature.execute()
    
    def show_chat(self) -> None:
        """显示对话界面"""
        # 使用对话功能模块
        chat_feature = ChatFeature(self)
        chat_feature.execute()
    
    def get_config(self) -> RagFlowConfig:
        """
        获取当前配置
        
        Returns:
            当前配置对象
        """
        return self.config
    
    def update_config(self, config: RagFlowConfig) -> None:
        """
        更新配置
        
        Args:
            config: 配置对象
        """
        # 检查是否切换了主题
        theme_changed = self.config.theme != config.theme
        
        # 更新配置
        self.config = config
        
        # 如果主题改变，应用新主题
        if theme_changed:
            logger.debug(f"主题已更改: {config.theme}")
            # 重新加载配置，确保从环境变量中获取最新值
            try:
                self.config = RagFlowConfig.from_env()
                logger.debug(f"重新加载配置后的主题: {self.config.theme}")
            except Exception as e:
                logger.error(f"重新加载配置失败: {str(e)}")
            
            # 强制设置主题
            self.config.theme = config.theme
            
            # 应用主题
            self.apply_theme()
    
    
    def on_batch_show_datasets(self) -> None:
        """处理批量上传选项卡中的显示知识库列表事件"""
        datasets_feature = DatasetsFeature(self)
        datasets_feature.execute()
    
    @Slot(int, int)
    def show_upload_result(self, success_count: int, failed_count: int) -> None:
        """
        显示上传结果
        
        Args:
            success_count: 成功数量
            failed_count: 失败数量
        """
        if failed_count == 0:
            QMessageBox.information(self, "成功", f"所有文件上传成功，共 {success_count} 个文件")
        else:
            QMessageBox.warning(self, "警告", f"部分文件上传失败，成功: {success_count}，失败: {failed_count}")
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        # 如果有正在运行的线程，停止它
        if self.current_thread and self.current_thread.isRunning():
            self.current_thread.cancel()
            self.current_thread.wait()
        
        # 接受关闭事件
        event.accept()


def run_pyside_gui() -> None:
    """运行 PySide6 GUI 应用"""
    try:
        # 创建应用
        app = QApplication(sys.argv)
        
        # 设置应用样式
        app.setStyle("Fusion")
        
        # 创建并显示主窗口
        window = RagFlowClientApp()
        window.show()
        
        # 运行应用
        sys.exit(app.exec())
        
    except Exception as e:
        print(f"启动 GUI 界面时出错: {str(e)}")


if __name__ == "__main__":
    run_pyside_gui()
